<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>防抖</title>
  </head>
  <body>
    <div style="height: 200vh; background-color: skyblue"></div>
    <script>
      // 浅谈 JS 防抖和节流(https://segmentfault.com/a/1190000018428170)
      function showTop() {
        var scrollTop =
          document.body.scrollTop || document.documentElement.scrollTop
        console.log('滚动条位置：' + scrollTop)
      }
      window.onscroll = debounce(showTop, 200)

      /*
       * 防抖
       * 在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则重新计时。
       */
      function debounce(fn, delay) {
        let timer = null
        return function () {
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(fn, delay)
        }
      }
    </script>
  </body>
</html>
